/**
 * 路由导航守卫
 * @function
 * @param {VueRouter} router 路由实例
 */
import { getAuth } from '@/base/api/auth';
import { save, get } from '@/utils/storage';
import cookie from '@/helper/cookie';
import { DESK_PATH } from '../config';
// 测试写入cookie
const testAuth = [
  { id: '1', name: '权限1' },
  { id: '2', name: '权限2' },
  { id: '3', name: '权限3' }
];
save('auth', transferAuth(testAuth));
function transferAuth(previlegeList) {
  let authMap = {};
  previlegeList.forEach(r => {
    authMap[r.id] = r.name;
  });
  return authMap;
}
function jumpLogin() {
  if (location.hash.includes('/task-feedback')) {
    window.location.href = `${location.pathname}#/login`;
  } else {
    window.location.href = DESK_PATH;
  }
}
console.log(DESK_PATH);
export default function(router) {
  /**
   * 全局前置守卫
   */
  router.beforeEach((to, from, next) => {
    let SESSION = to.query.session;
    // 保存session
    if (SESSION) {
      cookie('SESSION', SESSION)
    }
    // 如果有传session,则更新session,如果没传，也从cookie拿出来看看有没有
    let session = cookie('SESSION')
    let auth = get('auth');
    // 如果缓存有权限信息或者是登录页面，直接跳转
    if (auth || to.path === '/login') {
      next();
    } else {
      // 如果没有权限，又不是登录页，则看看有没有session,有session则获取权限，没有则跳到登录页
      if (session) {
        // 获取权限列表，如果获取权限失败，有可能token是不合法的，仍然跳到登陆页
        getAuth({})
          .then(res => {
            if (res) {
              save('auth', transferAuth(res));
              next();
            } else {
              next(false);
              jumpLogin();
            }
          })
          .catch(e => {
            next(false);
            jumpLogin();
          });
      } else {
        jumpLogin();
      }
    }
  });

  /**
   * 全局后置守卫
   */
  router.afterEach((to, from) => {
    // ...
  });
}
